package com.ys.controller.api.finance;

import com.bo.dto.NameValueDto;
import com.ys.config.MenuId;
import com.ys.entity.finance.TcwCapitalBusinessCost;
import com.ys.entity.finance.TcwCapitalClaim;
import com.ys.entity.finance.TcwCapitalRegisterClaim;
import com.ys.entity.finance.TcwCapitalRegisterClaim;
import com.ys.entity.flow.YspTaskAudit;
import com.ys.entity.flow.YspTaskAuditUser;
import com.ys.entity.shiro.LoginUser;
import com.ys.entity.sys.YsCol;
import com.ys.entity.sys.YsProcInst;
import com.ys.enume.flow.YspTaskAuditEnum;
import com.ys.enume.flow.YspTaskAuditUserEnum;
import com.ys.service.finance.TcwCapitalBusinessCostService;
import com.ys.service.finance.TcwCapitalClaimService;
import com.ys.service.finance.TcwCapitalRegisterClaimService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.PdfService;
import com.ys.service.sys.UploadService;
import com.ys.util.DateUtil;
import com.ys.util.ExportExcelUtils;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;

/**
 * 资金登记认领表
 */
@Controller
@RequestMapping("/api/inter/tcwCapitalRegisterClaim")
public class ApiInterTcwCapitalRegisterClaimController {
    private static final Logger logger = LoggerFactory.getLogger(ApiInterTcwCapitalRegisterClaimController.class);

    @Autowired
    private CommonApiService<TcwCapitalRegisterClaim> commonApiService;

    @Autowired
    private TcwCapitalRegisterClaimService tcwCapitalRegisterClaimService;

    @Autowired
    private TcwCapitalClaimService tcwCapitalClaimService;

    @Autowired
    private TcwCapitalBusinessCostService tcwCapitalBusinessCostService;


    @Autowired
    private PdfService pdfService;
    /**
     * 设置查询的cond的sql设置
     * @param cond
     * @return
     */
    public TcwCapitalRegisterClaim setSeachSql(TcwCapitalRegisterClaim cond){

        cond.addLeftJoin("TCW_CapitalRegisterSon S ON S.Id = A.CapitalRegisterSonId ")
                .addField("S.Pbid AS bid")//单号
                .addField("S.ClaimVgsmc AS claimVgsmc")//认领公司全称

                //.addLeftJoin("THR_OperateCompanyApply OC ON OC.Vgsbm = A.AccountingVgsbm ")
                //.addField("OC.Vgsjc AS accountingVgsjc")//收款运营公司简称

                .addField("'挂账账户' AS accountingVgsjc")//收款运营公司简称

                .addLeftJoin("TB_CompanyInfo C ON C.Vid = A.CompanyVid ")
                .addField("C.Vname AS companyVname")//收款公司名称

                .addLeftJoin("THR_OperateCompanyBankInfo CB ON CB.Id = A.OperateCompanyBankInfoId ")
                .addLeftJoin("THR_OperateCompanyApply OCB ON OCB.VgsBm = CB.Vgsbm ")
                .addLeftJoin("TS_UserChange UC on UC.Id = OCB.OperatorChangeId")
                .addField("UC.UserName cUserName")//运营人工号
                .addField("CB.Vid AS vid")//运营公司银行账户
                .addField("CB.Vyhzhmc AS vyhzhmc")//付款银行户名
                .addField("CB.Vkhh AS vkhh")//付款开户行
                .addField("CB.Vyhzh AS vyhzh")//付款银行账号
                .addField("CB.AccountType AS accountType")//账户类型
                .addField("CASE " +
                        "WHEN CB.AccountType = 0 THEN '对公户' " +
                        "WHEN CB.AccountType  = 1 THEN '个人户' " +
                        " ELSE '' END accountTypeTxt")//账户类型



                .addField("'运营服务→预付款' AS vjylx")//交易类型

                .addLeftJoin("THR_OperateCompanyApply OCA ON OCA.Vgsbm = A.ClaimVgsbm AND 1=1")
                .addField("OCA.Vgsjc AS claimVgsjc")//认领运营公司简称
                .addField("OCA.Vgsmc AS claimVgsmc")//认领运营公司名称
                //.where("A.CompanyVid is not null AND CB.Vid is not null")
                //.where("CB.Vid is null")


                //排序
        .setOrderby("S.Pbid DESC");

        cond = commonApiService.dataAuth(MenuId.TCW_CapitalRegisterClaim, cond);
        return  cond;
    }


    /**
     * 查询
     */
    @RequiresPermissions("tcwCapitalRegisterClaim:view")
    @RequestMapping("/search")
    @ResponseBody
    public LayuiTableVoJA search(Model model, HttpServletRequest request, HttpServletResponse response,
                                 @ModelAttribute TcwCapitalRegisterClaim cond,String conditions
    ){
        try {
            cond = setSeachSql(cond);
            return commonApiService.searchLay(cond);
        }catch (Exception e){
            logger.error("查询出错：",e.getMessage(),e);
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }
    }

    /**
     * 导出
     */
    @RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TcwCapitalRegisterClaim cond,String conditions){
        try {
            cond.setPage(0).setSize(999999);
            cond = setSeachSql(cond);
            //获取菜单字段数据
            List<YsCol> listField = new YsCol()
                    .setMenuId(MenuId.TCW_CapitalRegisterClaim)
                    .setFrontShow(1)
                    .setOrderby("A.SortNo asc")
                    .queryList();
            //获取数据
            List<Map<String, Object>> listData = cond.queryMap();

            //处理数据
            ExportExcelUtils<TcwCapitalRegisterClaim> util = new ExportExcelUtils<>(new TcwCapitalRegisterClaim());
            String toFilePath = util.exportExcel(listData, listField, "资金登记认领表");
            UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
            return R.ok(dto.getUrl());
        }catch (Exception e){
            logger.error("导出出错：",e.getMessage(),e);
            return R.error("导出失败，请稍后重试！");
        }
    }


    /**
     * 弹出框
     */
    @RequestMapping("/searchForModal")
    @ResponseBody
    public LayuiTableVoJA searchForModal(@ModelAttribute TcwCapitalRegisterClaim cond){
        cond.setStatus(1);
        cond.setClaimStatus(0);
        cond = setSeachSql(cond);
        return commonApiService.searchLay(cond);
    }


    /**
     * 退回
     */
    @RequestMapping("/toBack")
    @ResponseBody
    public R toBack(HttpServletRequest request,@RequestParam Map<String, Object> params){
        try {
            String ids = params.get("ids").toString();
            String[] idArr = ids.split(",");
            List<String> idList = new ArrayList<>();
            Collections.addAll(idList,idArr);
            int doCount = 0;
            String resMsg = "";
            for (int i = 0; i < idList.size(); i++) {
                //退回
                R res = tcwCapitalRegisterClaimService.toBack(Long.parseLong(idList.get(i)));
                if(res.getCode()==0){
                    doCount ++;
                }else{
                    resMsg += "所选的第"+(i+1)+"条信息："+res.getMsg()+"</br>";
                }
            }
            resMsg = "成功退回"+doCount+"条数据</br>"+resMsg;
            return R.ok(resMsg);
        } catch (Exception e) {
            logger.error("退回出错：",e.getMessage(),e);
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }
    }

    /**
     * 打印
     */
    @RequestMapping("/exportdy")
    @ResponseBody
    public R exportdy(HttpServletRequest request,@RequestParam("id") Long id) throws Exception {

        //预付款认领
        List<Map<String, Object>> tcwCapitalRegisterClaimList =
                setSeachSql(new TcwCapitalRegisterClaim())
                        .setId(id)
                        .queryMap();

        //预付款认领
        List<Map<String, Object>> infoByBusinessCost = tcwCapitalBusinessCostService
                .setSeachSql(new TcwCapitalBusinessCost())
                .where("CRC.Id = " + id + "")
                .queryMap();

        //资金登记认领
        List<Map<String, Object>> infoByClaim = tcwCapitalClaimService
                .setSeachSql(new TcwCapitalClaim())
                .where("C.Id = " + id + "")
                .queryMap();

        Map<String, Object> tcwCapitalRegisterClaim = tcwCapitalRegisterClaimList.get(0);
        Map<String, Object> sonByOne = null;
        if (infoByBusinessCost != null && infoByBusinessCost.size() > 0) {
            sonByOne = infoByBusinessCost.get(0);
        }

        if (infoByClaim != null && infoByClaim.size() > 0) {
            sonByOne = infoByClaim.get(0);
        }

        BigDecimal sonAmountTotal = BigDecimal.ZERO;
        for (Map<String, Object> son : infoByClaim) {
            sonAmountTotal = sonAmountTotal.add(new BigDecimal(son.get("paymentAmount").toString()));
        }

        String nameStr = (tcwCapitalRegisterClaim.get("vyhzhmc") != null ? tcwCapitalRegisterClaim.get("vyhzhmc").toString() : "")
                + "/" + (tcwCapitalRegisterClaim.get("vkhh") != null ? tcwCapitalRegisterClaim.get("vkhh").toString() : "")
                + "/" + (tcwCapitalRegisterClaim.get("vyhzh") != null ? tcwCapitalRegisterClaim.get("vyhzh").toString() : "");

        List<NameValueDto> listData = new ArrayList<>();
        listData.add(new NameValueDto("单据编号", tcwCapitalRegisterClaim.get("bid").toString()));
        listData.add(new NameValueDto("付款人及账号", nameStr));
        listData.add(new NameValueDto("付款时间", tcwCapitalRegisterClaim.get("paymentTime").toString()));
        listData.add(new NameValueDto("付款金额", tcwCapitalRegisterClaim.get("paymentAmount").toString()));
        listData.add(new NameValueDto("认领公司", sonByOne.get("claimVgsmc").toString()));
        listData.add(new NameValueDto("付款说明", ""));


        YsProcInst ysProcInst = new YsProcInst().setBid(sonByOne.get("bid").toString()).queryFirst();
        List<YspTaskAudit> listYspTaskAudit = new YspTaskAudit().setTaskId(ysProcInst.getTaskId()).queryList();
        List<Map<String, Object>>  auditDataList = new ArrayList<>();
        for(YspTaskAudit row : listYspTaskAudit) {
            Map<String, Object> auditDetails = new HashMap<>();

            // 拼接处理人
            String opeUsers = "";
            List<Map<String, Object>> listYspTaskAuditUser = new YspTaskAuditUser()
                    .setTaskId(ysProcInst.getTaskId())
                    .setTaskAuditId(row.getId())
                    .addLeftJoin("TS_UserInfo B ON B.UserId = A.UserId")
                    .addField("B.UserName userName")
                    .where("A.State in (" + YspTaskAuditUserEnum.State.FAILED.value + "," + YspTaskAuditUserEnum.State.SUCCESS.value + ")")
                    .queryMap();
            for(Map<String, Object> map : listYspTaskAuditUser) {
                opeUsers = tcwCapitalRegisterClaim.get("cUserName").toString();
            }


            auditDetails.put("processingTime", DateUtil.getYYYY_MM_DD_HH_mm_ss(row.getUpdateTime()));
            auditDetails.put("processingUser",opeUsers);
            auditDetails.put("processingResult", YspTaskAuditEnum.State.getName(row.getState()));
            auditDataList.add(auditDetails);
        }

        LoginUser loginUser = ShiroUtils.getLoginUser();
        String loginUserName = loginUser.getUserName();
        String loginUserUserId = loginUser.getUserId();
        String deptName = loginUser.getOrgName();

        String url = pdfService.generateZLY(sonByOne.get("bid").toString(),"预付款认领单", (sonByOne.get("depositPlatformName")!=null ? sonByOne.get("depositPlatformName").toString():""),
                sonByOne.get("createTimeByStr").toString(),listData,auditDataList,null,"打印人：" + loginUserUserId + "/" +loginUserName
                ,"打印人部门：" + deptName);
        return R.ok(url);
    }


}